import java.io.StringReader;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;
import org.wso2.carbon.registry.core.session.CurrentSession;


/*
 * <handler class="org.wso2.carbon.registry.lifecycle.accenture.sample.MovieEditorHandler">
        <filter class="org.wso2.carbon.registry.core.jdbc.handlers.filters.MediaTypeMatcher">
            <property name="mediaType">application/vnd.wso2-movie2+xml</property>
        </filter>
    </handler>

 */
public class MovieEditorHandler extends Handler {

	
	
	@Override
	public Resource get(RequestContext requestContext) throws RegistryException {
		String currentUserName = CurrentSession.getUser();
		if ("sumedha".equals(currentUserName)){
			//requestContext.setProcessingComplete(true);
			throw new RegistryException("Your not authorized to access this resource");
		}else{
			return super.get(requestContext);
		}
	}

	@Override
	public void put(RequestContext requestContext) throws RegistryException {
		Resource resource = requestContext.getResource();
		/*
		 * <metadata xmlns="http://www.wso2.org/governance/metadata"><overview><director>Anne Thomas</director><name>Jonny English</name></overview></metadata>
		 */
		
		
		String requestServiceString = (String) resource.getContent();
        XMLStreamReader reader = null;
        try {
            reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(requestServiceString));
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        
        OMElement serviceElement = builder.getDocumentElement();
        String xmlNs = serviceElement.getNamespace().getName();
        OMElement overviewOmElement = serviceElement.getFirstElement();
        OMElement nameOmElement = overviewOmElement.getFirstChildWithName(new QName(xmlNs, "name"));

        System.out.println("########## : "+nameOmElement.getText());
		
		super.put(requestContext);
	}

}

